<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>
    <h1 id="username"></h1>
    <textarea id="chat_content" readonly style="height: 400px;width: 600px;"></textarea>
    <br/>
    <textarea id="message" style="height: 100px;width: 100px;"></textarea>
    <button onclick="send_message()">发送</button>
    <script src="js/jquery.min.js"></script>
    <script>
        var websocketURL = new WebSocket("ws:127.0.0.1:8080/testAPI");
        //建立连接
        websocketURL.onopen = function() {
            console.log("建立连接");
            websocketURL.send("用户上线");
        }
        //接收消息
        websocketURL.onmessage = function(result) {
            let resp = JSON.parse(result.data);
            console.log("收到消息:"+result.data);
            if(resp.type == 0) {
                jQuery("#chat_content").append(resp.message+"\n");
            } else if(resp.type == 1) {
                jQuery("#username").val(resp.message);
            }
        }
        //连接异常
        websocketURL.onerror = function() {
            console.log("连接异常");
        }
        websocketURL.onclose = function() {
            console.log("断开连接");
            websocketURL.send("下线");
        }
        //发送消息
        function send_message() {
            var msg = jQuery("#message");
            if(msg.val() == "") {
                alert("输入为空");
                return;
            }
            websocketURL.send("用户："+msg.val());
        }
    </script>
</body>
</html>